/**
 * 
 */
package com.gopay.bis.web.controller.ebank;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.CebContants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ceb.ebank.CebB2cMessage;

/**
 * @CebB2cServerRes.java
 * @author Ryan
 * @2013-12-3 下午4:39:27 www.gopay.com.cn Inc.All rights reserved.
 */
@Controller
@Scope("prototype")
public class CebB2cServerRes extends BankResBase {
	
    private static Log logger = LogFactory.getLog(CebB2cServerRes.class);
    private static final String separator = "\\~\\|\\~";

    @RequestMapping(value = "/cebB2cServerRes")
    protected ModelAndView execute(HttpServletRequest request, HttpServletResponse response) {
        logger.error("--------------- CebB2cServerRes bankback ---------------");
        return super.execute(request, response);
    }

    @Override
    protected BaseMessage buildMessage(HttpServletRequest request) {
        CebB2cMessage message = new CebB2cMessage();
        // 银行返回的信息
        message.setResponseCode(request.getParameter("ResponseCode"));
        message.setPlainMessage(request.getParameter("Plain")); // 支付响应明文
        message.setSignMessage(request.getParameter("Signature")); // 支付响应密文
        parsePlainMessage(message);
        message.setAmount(new BigDecimal(message.getTransAmt()));
        message.setBankOrderId(message.getOrderId());
        message.setBank(BankConstants.BANK_LOGO_CEB);
        //银行业务产品00个人网银支付
        message.setBankBusProd(BisBankBusinessProd._00);
        return message;
    }

    @Override
    protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
        OrderInfo orderInfo = new OrderInfo();
        CebB2cMessage message = (CebB2cMessage) result.getModel("message");
    	if(message!=null){
			if(CebContants.CEB_RESPONSE_SUCC.equals(message.getResponseCode())){
		        orderInfo.setOrderId(message.getOrderId());
		        orderInfo.setAmt(String.valueOf(message.getAmount().longValue()));
		        orderInfo.setNotifyNum("1");
		        orderInfo.setPayStatus("00");
		        orderInfo.setRetCode("00");
		        orderInfo.setRetMsg("");
			}else{
				orderInfo.setOrderId(message.getOrderId());
		        orderInfo.setAmt(String.valueOf(message.getAmount().longValue()));
		        orderInfo.setNotifyNum("1");
		        orderInfo.setPayStatus("01");
		        orderInfo.setRetCode("01");
		        orderInfo.setRetMsg("");
			}
        StringBuffer notifyStr = new StringBuffer();
        orderInfo.setBankName("ceb");
        orderInfo.setIsNotify(true);
//        notifyStr.append("Plain=").append(message.getNotifyPlain());
//        notifyStr.append("\n");
//        notifyStr.append("Signature=").append(message.getNotifySign());
//        orderInfo.setRetMsg(notifyStr.toString());
    	}
        return orderInfo;
    }

    private void parsePlainMessage(CebB2cMessage cebMessage) {
        // 根据分隔符拆分出各个返回参数
        String[] reqParameters = cebMessage.getPlainMessage().split(separator);
        for (String param : reqParameters) {
            String[] paramCollection = param.split("=");
            {
                if (paramCollection.length > 1) {
                    if (paramCollection[0].equals("transId")) {
                        cebMessage.setTransId(paramCollection[1]);// 交易代码
                        continue;
                    }
                    if (paramCollection[0].equals("originalTransId")) {
                        cebMessage.setOriginalTransId(paramCollection[1]);// 原交易代码
                        continue;
                    }
                    if (paramCollection[0].equals("orderId")) {
                        cebMessage.setOrderId(paramCollection[1]);// 订单号
                        continue;
                    }
                    if (paramCollection[0].equals("transSeqNo")) {
                        cebMessage.setTransSeqNo(paramCollection[1]);// 支付系统交易流水号
                        continue;
                    }
                    if (paramCollection[0].equals("merchantId")) {
                        cebMessage.setMerchantId(paramCollection[1]);// 商户ＩＤ
                        continue;
                    }
                    if (paramCollection[0].equals("transDateTime")) {
                        cebMessage.setTransDateTime(paramCollection[1]);// 交易时间
                        continue;
                    }
                    if (paramCollection[0].equals("ppDateTime")) {
                        cebMessage.setPpDateTime(paramCollection[1]);// 支付系统交易时间
                        continue;
                    }
                    if (paramCollection[0].equals("clearingDate")) {
                        cebMessage.setClearingDate(paramCollection[1]);// 清算日期
                        continue;
                    }
                    if (paramCollection[0].equals("transAmt")) {
                        cebMessage.setTransAmt(paramCollection[1]);// 交易金额
                        continue;
                    }
                    if (paramCollection[0].equals("transAmt1")) {
                        cebMessage.setTransAmt1(paramCollection[1]);// 已退货金额
                        continue;
                    }
                    if (paramCollection[0].equals("feeAmt")) {
                        cebMessage.setFeeAmt(paramCollection[1]);// 手续费金额
                        continue;
                    }
                    if (paramCollection[0].equals("transStatus")) {
                        cebMessage.setTransStatus(paramCollection[1]);// 交易状态
                        continue;
                    }
                    if (paramCollection[0].equals("respCode")) {
                        cebMessage.setRespCode(paramCollection[1]);// 响应代码
                        continue;
                    }
                    if (paramCollection[0].equals("payAcctType")) {
                        cebMessage.setPayAcctType(paramCollection[1]);// 客户账户类型
                        continue;
                    }
                } else {
                    if (paramCollection[0].equals("transId")) {
                        cebMessage.setTransId(null);// 交易代码
                        continue;
                    }
                    if (paramCollection[0].equals("originalTransId")) {
                        cebMessage.setOriginalTransId(null);// 原交易代码
                        continue;
                    }
                    if (paramCollection[0].equals("orderId")) {
                        cebMessage.setOrderId(null);// 订单号
                        continue;
                    }
                    if (paramCollection[0].equals("transSeqNo")) {
                        cebMessage.setTransSeqNo(null);// 支付系统交易流水号
                        continue;
                    }
                    if (paramCollection[0].equals("merchantId")) {
                        cebMessage.setMerchantId(null);// 商户ＩＤ
                        continue;
                    }
                    if (paramCollection[0].equals("transDateTime")) {
                        cebMessage.setTransDateTime(null);// 交易时间
                        continue;
                    }
                    if (paramCollection[0].equals("ppDateTime")) {
                        cebMessage.setPpDateTime(null);// 支付系统交易时间
                        continue;
                    }
                    if (paramCollection[0].equals("clearingDate")) {
                        cebMessage.setClearingDate(null);// 清算日期
                        continue;
                    }
                    if (paramCollection[0].equals("transAmt")) {
                        cebMessage.setTransAmt(null);// 交易金额
                        continue;
                    }
                    if (paramCollection[0].equals("transAmt1")) {
                        cebMessage.setTransAmt1(null);// 已退货金额
                        continue;
                    }
                    if (paramCollection[0].equals("feeAmt")) {
                        cebMessage.setFeeAmt(null);// 手续费金额
                        continue;
                    }
                    if (paramCollection[0].equals("transStatus")) {
                        cebMessage.setTransStatus(null);// 交易状态
                        continue;
                    }
                    if (paramCollection[0].equals("respCode")) {
                        cebMessage.setRespCode(null);// 响应代码
                        continue;
                    }
                    if (paramCollection[0].equals("payAcctType")) {
                        cebMessage.setPayAcctType(null);// 客户账户类型
                        continue;
                    }
                }
            }
        }
    }

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		String responseCode = request.getParameter("ResponseCode");
        String plain = request.getParameter("Plain");
		String signature = request.getParameter("Signature");
		//返回的明文或密文有一项不存在，直接返回错误页面。
       if( StringUtils.isEmpty(plain) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(responseCode)){
    	  return false;
       }
       if("0000".equals(responseCode)){
    	   return true;
       }else{
    	   return false;
       }
	}
}
